//app.js
App({
  onLaunch: function () {
    //调用API从本地缓存中获取数据

    this.getUserInfo();
    this.getSwitchForVerify();
  },
  getUserInfo:function(cb){
    var that = this
    if(this.globalData.userInfo){
      typeof cb == "function" && cb(this.globalData.userInfo)
    }else{
      //调用登录接口
      wx.login({
        success: function (_data) {
          wx.request({
            url: `${that.globalData.serverHost}/wx/auth/get/sessionKey`, //仅为示例，并非真实的接口地址
            data: { code: _data.code },
            method: "post",
            header: { 'content-type': 'application/json'},
            success: function(res) {
              var _sessionKey = res.data.session_key;
              wx.getUserInfo({
                success: function (res) {
                  console.log(res);

                  wx.request({
                    url: `${that.globalData.serverHost}/wx/auth/get/userInfo`, //仅为示例，并非真实的接口地址
                    data: { 
                      rawData: res.encryptedData,
                      sessionKey: _sessionKey,
                      iv: res.iv
                    },
                    method: "post",
                    header: { 'content-type': 'application/json'},
                    success: function(res) {
                      that.globalData.userInfo = res.data;
                      typeof cb == "function" && cb(that.globalData.userInfo);
                      wx.request({
                        url: `${that.globalData.serverHost}/wx/save/user`, //仅为示例，并非真实的接口地址
                        data: that.globalData.userInfo,
                        method: "post",
                        header: { 'content-type': 'application/json'},
                        success: function(res) {
                        },
                        fail: function(res){
                          console.log(res);
                        }
                      });
                    },
                    fail: function(res){
                      console.log(res);
                    }
                  });
                }
              });
            },
            fail: function(res){
              console.log(res);
            }
          });
        },
        fail: function(){
          console.log("权限获取失败");
        }
      })
    }
  },
  getSwitchForVerify: function(){
    var that = this;
    wx.request({
      url: `${this.globalData.serverHost}/wx/get/verify`, //仅为示例，并非真实的接口地址
      method: "post",
      header: { 'content-type': 'application/json'},
      success: function(res) {
        that.globalData.switchForVerify = res.data.switchForVerify || false;
      },
      fail: function(res){
        console.log(res);
      }
    })
  },
  globalData:{
    userInfo:null,
    switchForVerify: false,
    serverHost: 'https://myfinder.cn',
  }
})